<?php
    class Cart extends MY_Controller {
    
        function init() {
            $this->resource = 'cart';
        }
            
        function index() {
            $view_data = array(
                'VIEW' => 'cart',                
            );
            $this->load->vars($view_data);
            $this->layout->load('cart');
        }
        
        function add($id) {
            $scart = $this->session->userdata('usercart');
            if($scart == FALSE) {
                $cart = array();                                
            } else {
                $cart = unserialize($scart);                
            }
            
            if(!isset($cart[$id])) {
                $cart[$id] = array('id' => $id, 'amount' => 0);                
            }
            $cart[$id]['amount']++;                        
            $dcart = serialize($cart);
            $this->session->set_userdata('usercart', $dcart);
            redirect('category/detail/'.$id, 'refresh');
        }
        
        function remove($id) {
            
        }
        
        function flush() {
            $this->session->set_userdata('usercart', NULL);
            redirect('cart', 'refresh');            
        }
        
        function confirm() {
            if($this->session->userdata('usercart') == NULL) {
                redirect('cart', 'refresh');    
            }
            if($this->input->post('cart_confirm_submit')) {
                $user_id = $this->system->getUserId();
                $cart = unserialize($this->session->userdata('usercart'));
                foreach($cart as $itemid => $stuff) {
                    $insert = array(
                        'user_id' => $user_id,
                        'stuff_id' => $itemid,
                        'amount' => $stuff['amount'],
                        'address' => $this->input->post('address'),                        
                    );
                    $this->db->insert('orders_devices', $insert);
                }
                $this->session->set_userdata('usercart', NULL);            
                $this->layout->load('cart_confirm_ok');
                return;
            }                                    
            $this->layout->load('cart_confirm');
        }
    }
?>